import search from '@/components/search0.vue';
import bannerSlider from './template/bannerSlider.vue';
import footNav from '@/components/footerNav.vue';
import indexMenu from './template/menu.vue';

import houseList from './template/houseSlider.vue';
import shortHouselist from './template/shortHouselist.vue';

import {mapState,mapMutations} from 'vuex';
import {reLoginWX} from '@/util/util.js';
import {MessageBox,Toast} from 'mint-ui';
// 高德地图js
import AMap from 'AMap';
// 引入vue-amap
import VueAMap from 'vue-amap';

// import VConsole from 'vconsole/dist/vconsole.min.js' //import vconsole
// let vConsole = new VConsole() // 初始化

export default {
  name: "index",
  data: () => ({
    bannerList:[],          //banner广告
    wholeHouselist:[],     //整租房源列表
    subletHouselist:[],    //转租房源列表
    shortRentHouselist:[],  //短租房源列表
    // token:'',              //用户授权token,Store里面定义
    // servicePhone:'',        //客服电话
    oCity:'',            //开通城市
    isAnyOtherCity:true,      //true:开通的城市有多个；false:当前暂未开通其他城市
    cityPoi:'',       //用户定位的城市
    isRealAuth:0,     //是否认证用户
  }),
  components: {
    bannerSlider,
    search,
    footNav,
    indexMenu,
    houseList,
    shortHouselist
  },
  computed:{
    //这里的三点叫做 : 扩展运算符
    ...mapState({
      token:state=>state.login.token,
      openCity:state=>state.house.openCity,
      servicePhone:state=>state.login.servicePhone,
      relogin:state=>state.login.relogin,
      // 相当于
      //show(){
      //     return this.$store.state.dialog.show;
      // }
    }),
  },
  created() {
    //do something after creating vue instance
    var that = this;
    // 页面创建的时候滚回顶部
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
    // let appId = 'wx8f2250783c3df196';   //微信appid
    let userToken = window.localStorage.getItem('userToken');   //获取缓存中的userToken
    let syOpenId = window.localStorage.getItem('syOpenId');     //获取缓存中的openi

    if (syOpenId==undefined || syOpenId=='null') {    //未授权
      reLoginWX();    //重新微信授权
    }else{
      if (userToken==undefined || userToken=='null') {  //未注册

      }else {   //已注册
        // 获取用户信息
        network.get(configUrl.QUERYUSER_URL,'',function(res){
          console.log(res);
          if(res.code==401){
            MessageBox.alert(res.message).then(action => {
                // that.$router.push({name:'login'});
                reLoginWX();
              }).catch(err=>{
                console.log(err);
              });
          }else{
            that.isLogin = true;
            that.userInfo = res.data;
            that.setUserInfo(res.data);
            window.localStorage.setItem('userInfo',JSON.stringify(res.data));
          }
        },function(err){
          console.log(err);
        });
      }

    }
    if(this.openCity){
      console.log(this.openCity);
    }else {
    var map = new AMap.Map("container", {
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function() {
      let geolocation = new AMap.Geolocation({
        // 是否使用高精度定位，默认：true
        enableHighAccuracy: true,
        // 设置定位超时时间，默认：无穷大
        // timeout: 10000,
        // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
        buttonOffset: new AMap.Pixel(10, 20),
        //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        zoomToAccuracy: true,
        //  定位按钮的排放位置,  RB表示右下
        buttonPosition: 'RB'
      })

      geolocation.getCurrentPosition();
      AMap.event.addListener(geolocation, 'complete', onComplete)
      AMap.event.addListener(geolocation, 'error', onError)

      function onComplete (data) {
        // data是具体的定位信息
        console.log(data);
        let addressComponent = data.addressComponent;
        that.cityPoi = addressComponent.city;     //用户当前定位的城市名称
        network.get(configUrl.OPENCITYBYNAME_URL,{cityName:addressComponent.city},function(res){
          console.log(res);
          if(res.data.isOpen==0){
            Toast('您所在的城市当前未开通');
            let defaultCity = data.defaultCity;
            that.setopenCity(defaultCity);    //存到state里面
            that.oCity = defaultCity.cityName;
            console.log(defaultCity);
          }else{
            that.setopenCity({areaId:res.data.cityId,areaName:addressComponent.city});    //存到state里面
            that.oCity = addressComponent.city;
          }
        },function(msg){
          console.log(msg);
        })
      }

      function onError (data) {
        // 定位出错
        console.log(data);
        Toast('获取定位失败，已为您切换到默认城市');
        network.get(configUrl.OPENCITYBYNAME_URL,{cityName:''},function(res){
          console.log(res);
          let defaultCity = res.data.defaultCity;
          that.setopenCity({areaId:defaultCity.cityId,areaName:defaultCity.cityName});    //存到state里面
          that.oCity = defaultCity.cityName;
        },function(msg){
          console.log(msg);
        })
      }
    });
    }
  },
  mounted() {
    //do something after mounting vue instance
    var that = this;
    if(that.relogin){
      that.$router.go(0);
    }
    // 获取用户信息
    network.get(configUrl.QUERYUSER_URL,'',function(res){
      console.log(res);
      that.isLogin = true;
      that.isRealAuth = res.data.isRealAuth;
    },function(err){
      console.log(err);
    });

    // 获取首页滚动广告
    that.getBannerList();
    // 获取整租
    that.getWholeRent(1,1,function(res){
      // console.log(res);
      that.wholeHouselist = res.dataList;

    });
    // 获取转租
    that.getWholeRent(1,4,function(res){
      // console.log(res);
      that.subletHouselist = res.dataList;
    });
    // 获取短租
    that.getWholeRent(2,'',function(res){
      // console.log(res);
      that.shortRentHouselist = res.dataList;
    });

    that.getServicePhone(); //获取客服电话

    let wxshareParam = {
      url:'http://rh.klbkvg.cn/index'
    }
    network.get(configUrl.WXSHAREPARAMS_URL,wxshareParam,function(res){
      console.log(res);
      // Toast('shareUrl='+shareUrl)
      //接口入住权限验证配置
       wx.config({
            // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。

            appId: res.appId, // 必填，公众号的唯一标识
            timestamp: res.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.nonceStr, // 必填，生成签名的随机串
            signature: res.signature, // 必填，签名，见附录1
            jsApiList: [
               'onMenuShareTimeline',
               'onMenuShareAppMessage',
               'onMenuShareQQ',
               'onMenuShareWeibo',
               'onMenuShareQZone'
          ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });

    },function(err){
      console.log(err);
    });
  },
  methods: {
    ...mapMutations([
      'setopenCity',
      'setServicePhone',
      'setUserInfo'
    ]),
    chooseCity () { //选择开通城市
      var that = this;
      if(that.isAnyOtherCity){
        that.$router.push({name:'cities',param:{}});
      }else{
        Toast('当前暂未开通其他城市');
      }
    },
    // 点击搜索事件
    toSearch() {
      this.$router.push({name:'searchPage'});
    },
    // 获取首页滚动广告
    getBannerList(){
      var that = this;
      network.get(configUrl.BANNERLIST_URL,'',function(res){
        // console.log(res);
        var dataList = res.dataList;
        that.bannerList = dataList;
      },function(err){
        console.log(err);
      });
    },
    // 获取整租房源列表
    getWholeRent(rentType,state,callback){
      var that = this;
      console.log(that.openCity);
      var wholeRentParam = {
        token:that.token,
        rentType:rentType,       //租赁类型 1长租 2短租
        cityId:that.openCity.areaId,        //城市id
        state:state,          //整租传1，转租传4
        currentPage:1,
        showCount:6
      }
      network.get(configUrl.HOUSELIST_URL,wholeRentParam,function(res) {
        callback(res);
      },function(err) {
        console.log(err);
      });
    },
    getServicePhone() {
      let that = this;
      // 客服电话
      network.get(configUrl.SERVERPHONE_URL,'',function (res) {
        // console.log(res);
        var servicePhone = res.data.servicePhone;
        that.setServicePhone(servicePhone);
      },function (error) {
        console.log(error);
      });
    },
    callService(){
      console.log(this.servicePhone);
      window.location.href = 'tel://'+this.servicePhone;
    }

  },
  updated: function () {
    var that = this;
    this.$nextTick(function () {
      // Code that will run only after the
      // entire view has been re-rendered
      // that.openCity = that.global.global.openCity;
      if(that.openCity){
        that.oCity = that.openCity;
        console.log(that.oCity);
      }else{
        that.oCity = '开通城市'
      }

    })
  }
}
